import { reqCartList,reqDeleteCartById,reqUpdateCheckedById } from "@/api"
// import { ownKeys } from "core-js/fn/reflect"
const state = {
    cartList:[]
}
const mutations = {
    GETCARTLIST(state,cartList) {
        state.cartList = cartList
    }
}
const actions = {
    // 获取购物车列表
    async getCartList({ commit }) {
        let result = await reqCartList()
        if (result.code == 200) {
            commit("GETCARTLIST", result.data)
        }
    },
    // 删除购物车产品
    async deleteCartListBySkuId({ commit }, skuId) {
        let result = await reqDeleteCartById(skuId)
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    // 修改购物车选中状态
    async updateCheckedById({ commit }, { skuId, isChecked }) {
        let result = await reqUpdateCheckedById(skuId, isChecked)
        if (result.code == 200) {
            return "ok"
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    deleteAllCheckedCart({ dispatch, getters }) {
        // console.log(context);
        // context：小仓库，commit【提交mutations，修改state】getters【计算属性】dispatch【派发数据】state【当前仓库数据】
        // 获取购物车当中全部的产品【数组】
        let PromiseAll = []
        getters.cartList.cartInfoList.forEach(element => {
            let Promise = element.isChecked == 1 ? dispatch('deleteCartListBySkuId', element.skuId) : ''
            // 将每一个返回的Promise添加到数组当中
            PromiseAll.push(Promise)
        });
        // 只要全部的都删除成功，才成功，只要有一个失败，就会返回失败
        return Promise.all(PromiseAll)
    },
    // 修改全选按钮的状态
    updateAllChecked({dispatch, state},isChecked) {
        let PromiseAll = []
        state.cartList[0].cartInfoList.forEach((item) => {
            let Promise = dispatch('updateCheckedById', {
                skuId: item.skuId,
                isChecked
            })
            PromiseAll.push(Promise)
        })
        // 最终返回结果
        return Promise.all(PromiseAll)
    }
}
const getters = {
    cartList(state) {
        return state.cartList[0]||{}
    }
}
export default {
    state,
    mutations,
    actions,
    getters
}